package com.mxchip.livestar.ui.call


import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager

import com.mxchip.livestar.R
import com.mxchip.livestar.base.SystemData
import com.mxchip.livestar.base.hideKeyboard
import com.mxchip.livestar.repository.RoomClientRepository
import com.mxchip.livestar.ui.GridItemDecoration
import com.videohigh.graham.SampleSDK
import kotlinx.android.synthetic.main.fragment_admin.*

class AdminFragment : Fragment(), TextWatcher, TextView.OnEditorActionListener {

    private val adminViewModel by viewModels<AdminViewModel>()

    private val dbyViewModel by activityViewModels<DbyViewModel>()
    private val roomViewModel by activityViewModels<RoomViewModel>()

    // private val sampleSDK = SampleSDK.getInstance()

    private val adminAdapter: AdminAdapter by lazy {
        AdminAdapter(this::onItemClick)
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        adminViewModel.searchWord(if (count > 0) s.toString() else null)
    }

    override fun afterTextChanged(s: Editable) {}

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            val keyword = v?.text?.toString()
            // 当按了搜索之后关闭软键盘
            hideKeyboard()
            /*(Objects.requireNonNull(context)!!.getSystemService(
                    Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
                    Objects.requireNonNull(Objects.requireNonNull(activity)!!.currentFocus).windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)*/
            //搜索
            return keyword.isNullOrBlank()
        }
        return false
    }

    private fun onItemClick(v: View, avUser: AVUser) {

        val action = AdminFragmentDirections.actionAdminFragmentToAdminMuteDialogFragment()

        action.term = avUser.term
        action.userName = avUser.name

        findNavController().navigate(action)
    }

    override fun onDestroyView() {
        super.onDestroyView()

        (activity as AppCompatActivity).supportActionBar?.hide()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.fragment_admin, container, false)
    }


    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        contact_search_key2.addTextChangedListener(this)
        contact_search_key2.setOnEditorActionListener(this)
        (activity as AppCompatActivity).supportActionBar?.show()


        val gridLayoutManager = GridLayoutManager(context, 2)
        recycler_view.showEmpty()
        recycler_view.addItemDecoration(GridItemDecoration(Color.TRANSPARENT, 0, 0, Color.TRANSPARENT, 0))
        recycler_view.setLayoutManager(gridLayoutManager)

        recycler_view.adapter = adminAdapter


        adminViewModel.micUserIds.observe(viewLifecycleOwner, Observer {
            textView2.text = "${it.size} 路音频"
        })

        roomViewModel.avDevices.observe(viewLifecycleOwner, Observer { device ->

            val list = device.filter {
                it.deviceName == AVDevice.CAMERA_LOCAL || it.deviceName == AVDevice.CAMERA_LOCAL_SMALL
            }.distinctBy { it.term }

            textView3.text = "${list.size} 路视频"
        })

        roomViewModel.avDevices.observe(viewLifecycleOwner, Observer { device ->

            val list = device.filter {
                it.deviceName == AVDevice.CAMERA_WIFI || it.deviceName == AVDevice.CAMERA_HDMI
            }

            textView4.text = "${list.size} 路屏幕共享"
        })

        adminViewModel.meetingFilterList.observe(viewLifecycleOwner, Observer { list ->
            val users = arrayListOf<AVUser>()

            list.forEach {
                if(it.term.roomId == SystemData.roomId() && it.term.termId == SystemData.userId()) {
                    users.add(0, it)
                } else {
                    users.add(it)
                }
            }
            adminAdapter.data = users
            adminAdapter.notifyDataSetChanged()
        })

        adminViewModel.avUsers.observe(viewLifecycleOwner, Observer { list ->
            textView8.text = "共 ${list.size} 会议参与者"
        })

        button_mute_audio.setOnClickListener {
            roomViewModel.audioDevices.value?.let { list ->
                RoomClientRepository.mgtMuteAudio(list.map { it.term }.toTypedArray())
            }
        }

        button2.setOnClickListener {
            roomViewModel.avDevices.value?.let { list ->
                val terms = list.map { it.term }.distinct().toTypedArray()
                if (terms.isEmpty())
                    return@let
                RoomClientRepository.mgtMuteCamera(terms)
            }
        }

        button3.setOnClickListener {
            roomViewModel.avDevices.value?.let { list ->
                val terms = list.map { it.term }.distinct().toTypedArray()
                if (terms.isEmpty())
                    return@let
                RoomClientRepository.mgtMuteShareContent(terms)
            }
        }
    }

}

